package leetcode;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2022-03-13 23:00
 **/
public class LeetCode393 {

    static final int MASK1 = 1 << 7;
    static final int MASK2 = (1 << 7) + (1 << 6);

    public boolean validUtf8(int[] data) {
        int m = data.length;
        int index = 0;
        while (index < m) {
            //获取data[index]表示字符的字节长度
            int n = getBytes(data[index]);
            if (n < 0 || index + n > m) {
                return false;
            }

            //判断后面的n-1位字符的有效位是否以10开头
            for (int i = 1; i < n; ++i) {
                if (!isValid(data[index + i])) {
                    return false;
                }
            }
            index += n;
        }
        return true;
    }

    public int getBytes(int num) {
        //首位有效位为0,说明是1字节字符
        if ((num & MASK1) == 0) {
            return 1;
        }

        int m = MASK1;
        int n = 0;
        //获取字节长度
        while (((m & num) != 0)) {
            ++n;
            //n <= 4
            if (n > 4) {
                return -1;
            }
            //掩码右移一位
            m >>= 1;
        }

        return n >= 2 ? n : -1;
    }

    public boolean isValid(int num) {
        return (num & MASK2) == MASK1;
    }

}
